/**
 * @desc:新平安绑卡
 */

import { useState, useEffect, useRef } from 'react';
import {
  Form,
  Button,
  Input,
  Checkbox,
  Alert,
  Select,
  Tooltip,
  Modal,
  message,
} from 'antd';
import { CloseCircleOutlined } from '@ant-design/icons';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import BankLimitModal from './BanKLimitModal';
import AccountState from './AccountState';
import BindCardList from './BindCardList';
import { cloneDeep, find } from 'lodash';
import {
  getLimitBankListOp,
  bindCardSendSmsOp,
  preCheckOp,
  openAndBindCardOp,
  queryPingAnAccount,
} from './service';

export const layout = {
  labelCol: {
    span: 7,
  },
  wrapperCol: {
    span: 16,
  },
};

const linkMap = {
  1: 'https://www.zhaojiafang.com/shopping/policy?article_title=个人资金存管服务协议',
  2: 'https://www.zhaojiafang.com/shopping/policy?article_title=平安银行电子II、III类户服务协议',
  3: 'https://www.zhaojiafang.com/shopping/policy?article_title=个人银行结算账户跨行收/付款服务协议',
  4: 'https://www.zhaojiafang.com/shopping/policy?article_title=扩展业务功能个人信息单独授权条款',
};

const { Option } = Select;

const NewBindCardModal = ({
  params,
  accountExtend,
  handleOk,
  handleCancel,
  handleAllCancel,
}) => {
  const [form] = Form.useForm();

  const [loading, setLoading] = useState(false);

  const [visible, setVisible] = useState(false);

  const [bankList, setBankList] = useState([]);

  const [selectBankItem, setSelectBankItem] = useState({}); //选中的银行信息

  const [countDown, setCount] = useState(0);

  const [pingAnAccount, setPingAnAccount] = useState({}); //平安账户状态和绑卡信息

  const [updateKey, setUpdateKey] = useState(0);

  const stageData = useRef({
    checkResult: undefined,
    businessNo: undefined,
    otpOrderNo: undefined,
    checkBoxOne: false,
    checkBoxTwo: false,
  });

  useEffect(() => {
    // const baseDataItem = getBaseData('bankList');
    // if(baseDataItem){
    //   setBankList(baseDataItem);
    // }else{
    //   getList();
    // }
    getList();
  }, []);

  useEffect(() => {
    if (countDown) {
      setTimeout(() => {
        setCount(countDown - 1);
      }, 1000);
    }
  }, [countDown]);

  // 获取开户行下拉
  const getList = async () => {
    const res = await getLimitBankListOp();
    if (res.success) {
      const { data } = res;
      setBankList(data);
      // setBaseData('bankList', data);
    }
  };

  // 查询平安账户状态和绑卡信息
  const getPingAnAccount = async (isCheck) => {
    setLoading(true);
    const res = await queryPingAnAccount();
    if (res.success) {
      const { data = {} } = res;
      setPingAnAccount(data);
      if (isCheck) {
        // isCheck是否需要验证锁定
        if (data.status == 1 || data.status == 2) {
          //异常或者锁定
          setVisible('AccountState');
        } else if (data.status == 0) {
          //正常
          if (data.bindcardList && data.bindcardList.length > 0) {
            //已绑卡
            setVisible('BindCardList');
          }
        }
      }
    }
    setLoading(false);
  };

  //选择银行
  const bankSelect = (e) => {
    const obj = find(bankList, ['name', e]);
    setSelectBankItem(obj);
  };

  const errorBindCardTips = () => {
    Modal.error({
      icon: '',
      content: (
        <>
          <span className="common-color9" style={{ fontSize: '16px' }}>
            <CloseCircleOutlined />
            &nbsp;&nbsp;绑卡失败
          </span>
          <p style={{ paddingLeft: 24 }}>该银行卡号不支持绑定，请换一张卡</p>
        </>
      ),
      onOk() {
        form.setFieldsValue({ bankNo: '' });
      },
    });
  };

  //获取验证码,并开始倒计时
  const handleGetCode = async () => {
    form.validateFields(['bankNo', 'mobile']).then(async (value) => {
      if (!stageData.current.checkResult) {
        return errorBindCardTips();
      }
      setLoading(true);
      const { data, success } = await bindCardSendSmsOp({ ...value });
      if (success) {
        const { businessNo, otpOrderNo } = data || {};
        stageData.current = { ...stageData.current, businessNo, otpOrderNo };
        setCount(59);
        message.success('验证码发送成功!');
      }
      setLoading(false);
    });
  };

  //代扣签约前置检查
  const blurCheckBank = async (value) => {
    if (value) {
      const bankNo = value.replaceAll(' ', '');
      if (bankNo && bankNo != stageData.current.prevBankNo) {
        setLoading(true);
        const { data, success } = await preCheckOp({ bankNo });
        if (success) {
          stageData.current.checkResult = data;
        } else {
          stageData.current.checkResult = false;
        }
        stageData.current.prevBankNo = bankNo;
        setLoading(false);
        setUpdateKey(updateKey + 1);
        form.setFieldsValue({ bankNo, smsCode: '' });
      }
    }
  };

  //开户绑卡一体化流程
  const onOk = () => {
    form.validateFields().then(async (value) => {
      const { checkResult, checkBoxOne, checkBoxTwo } = stageData.current;
      if (!checkBoxOne || !checkBoxTwo) {
        return message.info('请勾选和同意用户条款');
      }
      if (!checkResult) {
        return errorBindCardTips();
      }
      setLoading(true);
      const res = await openAndBindCardOp({
        ...value,
        ...params.current,
        ...stageData.current,
        front: undefined,
        back: undefined,
        checkBoxOne: undefined,
        checkBoxTwo: undefined,
        prevBankNo: undefined,
      });
      if (res.success) {
        handleOk(); //更新数据
        // data == 2开户 == 3授权
        if (res.data == 2) {
          message.success('开户成功！');
          handleCancel();
          handleAllCancel();
        } else if (res.data == 3) {
          getPingAnAccount(true);
        }
      } else {
        form.setFieldsValue({ smsCode: '' });
        setUpdateKey(updateKey + 1);
        setLoading(false);
      }
    });
  };

  //账号状态
  const AccountStateProps = {
    visible: visible == 'AccountState',
    pingAnAccount,
    handleCancel() {
      setVisible(false);
    },
    handleOk() {
      setVisible(false);
      getPingAnAccount(true);
    },
  };

  //绑定银行卡列表
  const BindCardListProps = {
    noMesRequire: false, //需验证码验证
    visible: visible == 'BindCardList',
    accountExtend,
    pingAnAccount,
    handleCancel() {
      setVisible(false);
    },
    handleOk() {
      handleOk();
      handleAllCancel();
      setVisible(false);
    },
    handleUnBindOk() {
      //解绑卡
      getPingAnAccount(false);
    },
  };

  return (
    <CommonModal
      title="绑定银行卡"
      visible={true}
      width="488px"
      onCancel={handleCancel}
      onOk={onOk}
    >
      <Alert message="绑定银行卡，即可激活平安电子账户用于交易" />

      <Form
        name="new-bind-card-form"
        form={form}
        {...layout}
        style={{ marginTop: '8px' }}
      >
        <Form.Item label="姓名">
          <div>{accountExtend?.userName}</div>
        </Form.Item>

        <p style={{ textAlign: 'right', padding: '0 20px 2px 0' }}>
          <span className="common-color2" onClick={() => setVisible(1)}>
            查看支持银行和充值限额
          </span>
        </p>

        <Form.Item
          label="开户银行"
          name="bankName"
          rules={[{ required: true, message: '请选择开户银行' }]}
          extra={
            <div>
              <div className="common-color9">
                单日充值限额：{' '}
                {selectBankItem.dayMoney ? selectBankItem.dayMoney : ''}
              </div>
              <span className="common-color9">
                注：建议选择限额较高的银行卡进行绑定
              </span>
            </div>
          }
        >
          <Select
            placeholder="请选择开户银行"
            optionFilterProp="label"
            showSearch
            allowClear
            onChange={(e) => bankSelect(e)}
          >
            {bankList.length &&
              bankList.map((d) => (
                <Option key={d.name} label={d.name}>
                  <Tooltip
                    title={
                      <>
                        <span>{d.name}</span>
                        <span>
                          {d.oneMoney && d.oneMoney.includes('万')
                            ? `（限额${d.oneMoney}）`
                            : `（${d.oneMoney}）`}
                        </span>
                      </>
                    }
                  >
                    {d.name}
                    {d.oneMoney && d.oneMoney.includes('万')
                      ? `（限额${d.oneMoney}）`
                      : `（${d.oneMoney}）`}
                  </Tooltip>
                </Option>
              ))}
          </Select>
        </Form.Item>

        <Form.Item
          label="银行卡号"
          name="bankNo"
          rules={[{ required: true, message: '请输入银行卡号' }]}
        >
          <Input
            onBlur={(e) => blurCheckBank(e.target.value)}
            autoComplete="off"
          />
        </Form.Item>

        <Form.Item
          label="银行预留手机号"
          name="mobile"
          rules={[
            { required: true, message: '请输入银行预留手机号' },
            { pattern: /^1[3456789]\d{9}$/, message: '请输入正确的手机号!' },
          ]}
        >
          <Input maxLength={11} autoComplete="off" />
        </Form.Item>

        <Form.Item
          label="手机验证码"
          name="smsCode"
          rules={[{ required: true, message: '请输入手机验证码' }]}
          key={updateKey}
        >
          <div className="flex">
            <Input maxLength={6} autoComplete="off" />
            <Button
              style={{ marginLeft: 24 }}
              onClick={handleGetCode}
              disabled={countDown}
            >
              获取验证码{countDown ? `(${countDown})` : ''}
            </Button>
          </div>
        </Form.Item>
      </Form>
      <div style={{ paddingLeft: '58px' }}>
        <Checkbox
          onChange={(e) => (stageData.current.checkBoxOne = e.target.checked)}
        />
        &nbsp;&nbsp;我已阅读并同意
        <a type="link" href={linkMap[1]} target="blank">
          《个人资金存管服务协议》
        </a>
        <br />
        <Checkbox
          onChange={(e) => (stageData.current.checkBoxTwo = e.target.checked)}
        />
        &nbsp;&nbsp;我已阅读并同意
        <a type="link" href={linkMap[2]} target="blank">
          《平安银行电子II、III类户服务协议》
        </a>
        、
        <a type="link" href={linkMap[3]} target="blank">
          《个人银行结算账户跨行收付款服务协议》
        </a>
        、
        <a type="link" href={linkMap[4]} target="blank">
          《扩展业务功能个人信息单独授权条款（电子II、III类,个人银行结算账户）》
        </a>
      </div>
      <BankLimitModal
        visible={visible == 1}
        handleClose={() => setVisible(false)}
        bankList={bankList}
      />
      {/* 账户状态 */}
      {visible == 'AccountState' && <AccountState {...AccountStateProps} />}
      {/* 绑定银行卡列表 */}
      {visible == 'BindCardList' && <BindCardList {...BindCardListProps} />}
      <CommonLoading loading={loading} />
    </CommonModal>
  );
};

export default NewBindCardModal;
